import 'dart:io';
import 'dart:convert';
import 'dart:typed_data';
import 'package:dio/dio.dart';
import 'package:crypto/crypto.dart';
import 'package:flutter_elf/utils/get_utils.dart';
import 'package:http/http.dart' as http;

import '../download/file_utils.dart';
import '../emoj_test.dart';
import 'ZhiYaoModel.dart';

String filePath = 'C:\\Users\\user\\Desktop\\知妖图片';
void main()async{

  for(int i = 0;i <= 33;i++){
    ZhiYaoModel model = await getModel(i);
    await downLoadPictures(model);
//    upgradeData(model);
  }
  await Future.delayed(Duration(seconds: 1000));
}

///下载图片
downLoadPictures(ZhiYaoModel model)async{
  model.data.forEach((item)async{
    item.pics.split(',').forEach((url)async{
      print('下载$url');
      if(isEmptyString(url)){
        return;
      }
      try{
        Uint8List picture = await HttpUtils.getFile(url);
        if(picture.lengthInBytes < 10000){
          return;
        }
        await FileUtils.saveFile(filePath + "\\"+ getFileName(url), picture);
      }catch(e){

      }
    });
  });
}

String getFileName(String path){
  String sub = path.substring(path.lastIndexOf('/')+1,path.length);
  String result = '';

  return sub;
}

Future<ZhiYaoModel> getModel(int page)async{
  String url = 'http://localhost:8888/article/$page/10';
  print('请求连接 ++ $url');
  http.Response res = await http.get(url,headers: {
    "Authorization":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJmbHV0dGVyX2VsZiIsImV4cCI6MTU5NjI2NzQ3MywiZGF0YSI6eyJpVXNlcklkIjo2fX0.H666ntO_piGbgGrdcmJyahgVQiO5tI-hrpjAxv3YpPw"
  });
  ZhiYaoModel model = ZhiYaoModel.fromJson(json.decode(res.body));
  return model;
}

///修改数据了
upgradeData(ZhiYaoModel model)async{
  model.data.forEach((item)async{
    await update(item);
  });
}

update(ZhiYaoData data)async{
  String url = 'http://81.68.107.3:8888/article/${data.iArticleId}';
  if(isEmptyString(data.pics)){
    return;
  }
  data.pics = data.pics.split(',').map((pic){
    return getFileName(pic);
  }).toList().join(',');
  http.Response res = await http.put(url,headers: {
    "Authorization":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJmbHV0dGVyX2VsZiIsImV4cCI6MTU5NjI2NzQ3MywiZGF0YSI6eyJpVXNlcklkIjo2fX0.H666ntO_piGbgGrdcmJyahgVQiO5tI-hrpjAxv3YpPw",
    "Content-Type":"application/json"
  },body: json.encode(data.toMap()));
//  print(data.toMap());
  print( "是否修改成功" + res.body);
}

Future<File> getFile(int offset){

  return null;
}

Future<String> uploadPicture(String filePath,String fileName)async{
  String policyText = '{"expiration": "2020-07-31T15:05:00.000Z","conditions": [["content-length-range", 0, 1048576000]]}';
  //进行utf8编码
  List<int> policyTextUtf8 = utf8.encode(policyText);
  //进行base64编码
  String policyBase64 = base64.encode(policyTextUtf8);
  //再次进行utf8编码
  List<int> policy = utf8.encode(policyBase64);
  String accessKey = '276m7TZRHkCngQKlQ6N46u0lZZaplT';
  //进行utf8 编码
  List<int> keys = utf8.encode(accessKey);
  //通过hMac,使用sha1进行加密
  List<int> signaturePre = new Hmac(sha1, keys).convert(policy).bytes;
  //最后一步，将上述所得进行base64 编码
  String signature = base64.encode(signaturePre);
  //dio的请求配置，这一步非常重要！
  BaseOptions options = new BaseOptions();
  options.responseType = ResponseType.plain;

  //创建dio对象
  Dio dio = new Dio();
  dio.options = options;
  //文件名
  //创建一个formData，作为dio的参数
  FormData data = new FormData.fromMap({
    'Filename': '$fileName',
    'key': "zhiyao_picture/" + fileName,
    'policy': policyBase64,
    'OSSAccessKeyId': 'LTAI4GKZ2Z3tiSpev8QXoxXE', //TODO
    'success_action_status': '200', //让服务端返回200，不然，默认会返回204
    'signature': signature,
    'file': await MultipartFile.fromFile(filePath,filename: '$fileName')
  });
  try {
    Response response = await dio
        .post('https://chen412115.oss-cn-beijing.aliyuncs.com', data: data);
    print('上传' + response.headers.toString());
    print('上传' + response.data);
  } on DioError catch (e) {
    print('上传' + e.message);
    print('上传' + e.response.data);
    print('上传' + e.response.headers.toString());
    print('上传' + e.response.request.toString());
  }
  return '';
}